package Sort;

public class sort5 {
    //冒泡排序
    public static void main(String[] args) {
        int[] arr = {10, 5, 21, 6, 7, 2, 9, 11, 3, 1};
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        bubbleSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    private static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length-1 ; i++) {
            boolean flag = false;
            for (int j = 0 ; j < arr.length-1-i; j++) {

                if (arr[j] > arr[j+1]) {
                    swap(arr, j+1, j);
                    flag = true;
                }
            }
            //如果一次都没有交换说明已经有序没有必要交换
            if(flag == false){
                return;
            }

        }
    }

    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }
}
